const log4js      = require('../../utils/logUtils');
const logger      = log4js.getLogger('web');
const constants   = require('../../db/constants');
const channelModel= require('../../model/channel');
const server      = require('../../sip/server/server');
const mediaServerModel = require('../../model/mediaServer');
const deviceModel = require('../../model/device');
const baseCtrl    = require('./basectrl');
const deviceCache = require("../../db/deviceCache");
const zlMediaKitApi = require("../../service/ZlMediaKitApi");
/**
 * 子通道
 */
const TAG = "[通道控制器]";
let Channel = {

    list:async function(req,res){
        // TODO: 外部接口会用到，暂时去掉了验证
        // if(!basectrl.hasLogin(req, res)){
        //     return;
        // }
        channelModel.list(req.query.parentId).then(async (rows) => {
            // TODO:生成 hls 地址
            let handleRows = [];

            // 获取 device 信息
            const device = await deviceModel.getDeviceByDeviceId(req.query.parentId);
            let serverId;
            if (device && device.server_id_zlk) {
                serverId = device.server_id_zlk;
            } else {
                serverId = 1;
            }
            // 从host是为了获取url urlTls等信息
            let hostModel = await mediaServerModel.getInfoById(serverId);

            for (let i = 0; i < rows.length; i++) {
                const item = rows[i];
                //TODO: 海康大华的，如果通道大于1，那deviceid和parentid相等就不能用
                // 但JCO的设备，通道等于2时, deviceid和parentid相等是能用的
                // if (rows.length > 2 && item.deviceid === item.parentid) {
                //     // nvr 的这个通道不用
                //     await that.generateUrl(hostModel, item, 'rtp');
                // } else {
                //     handleRows.push(item);
                // }
                item.channel_id = item.deviceid;
                item.deviceid = item.parentid;
                channelModel.generateUrl(hostModel, item, 'rtp');
                handleRows.push(item);
                logger.info(TAG, "这时的item值", item);
            }

            // 处理逻辑 ...
            let ret =Object.assign(constants.httpCode.OK , {data:{items:handleRows, total:handleRows.length}});
            res.send(ret);
        }).catch((err) => {
            logger.error('请求列表出现异常', err);
            res.send({'code':1, 'msg':'出现异常' + err});
        });
    },
    deleteByChannelDevice:async function(req, res){
        if(!baseCtrl.hasLogin(req, res)){
            return;
        }
        const parentId = req.body.parentId;
        const deviceId = req.body.deviceId;

        channelModel.deleteByDeviceId(parentId, deviceId);
        // 删除缓存信息
        if(deviceCache.registry && constants.registry[parentId] && constants.registry[parentId][deviceId]){
            delete deviceCache.registry[parentId][deviceId];
        }
        let ret =Object.assign(constants.httpCode.OK , {data:{}});
        res.send(ret);
    },
    // 发停止播放指令
    bye: async function (req, res) {
        if (!baseCtrl.hasLogin(req, res)) {
            return;
        }
        logger.log('bye req', req.query);
        let deviceid = req.query.deviceId;
        let channel = req.query.channelId;
        await server.bye(deviceid, channel);
        res.send({'code': 0, 'msg': 'success'});
    },
    // 截屏
    snap: async function (req, res) {
        // 暂时注销，可能会导致无法截屏
        // if(!basectrl.hasLogin(req, res)){
        //     return;
        // }
        logger.info(TAG, '截图请求', req);
        let deviceId = req.query.deviceId;
        let channelId = req.query.channelId;
        let url = channelModel.calcMediaUrl(deviceId, channelId, 'local',null,'rtp');
        // 暂时不截图了，直接返回在线结果
        const ret = await deviceModel.getDeviceByDeviceId(deviceId);
        const channels = await channelModel.list(deviceId);
        logger.info(`数据库结果,deviceId=${deviceId},channel=${channelId}`, ret, channels);

        zlMediaKitApi.snap(url, deviceId, channelId).then((ret) => {
            logger.info(`截图返回,deviceId=${deviceId},channel=${channelId}`,ret);

            channelModel.updateSnap(ret.toString(), deviceId, channelId).then(() => {
                logger.info(`截图更新成功,deviceId=${deviceId},channel=${channelId}`,ret);
                res.send(Object.assign(constants.httpCode.OK, {data: {}}));
            }).catch((err) => {
                logger.info(`截图更新失败,deviceId=${deviceId},channel=${channelId}`,err);
                res.send(Object.assign(constants.httpCode.ILLEGAL_PARAM, {data: {}}));
            })

        }).catch((err) => {
            logger.info(`截图异常,deviceId=${deviceId},channelId=${channelId}`, err);
            res.send(Object.assign(constants.httpCode.UNKNOWN, {data: {}}));
        });
        res.send(Object.assign(constants.httpCode.OK, {data: {
            'items':ret,
            'channels':channels
            }}));
    },
    // 国标获取录像列表
    sendGbRecordListCommand:function(req,res){
        if(!baseCtrl.hasLogin(req, res)){
            return;
        }
        let deviceId = req.query.deviceId;
        let channelId = req.query.channelId;
        if(!deviceId || !channelId){
            res.send(Object.assign(constants.httpCode.ILLEGAL_PARAM, {data: {}}));
            return;
        }

        server.recordList(deviceId, channelId, req.query.startTime, req.query.endTime).then(
            (SN) => {
                logger.info(TAG, "发送查询录像列表命令成功");
                res.send(Object.assign(constants.httpCode.OK, {data: {SN}}));
            }
        ).catch((err) => {
            logger.error(TAG, "获取录像列表失败", err);
            res.send(Object.assign(constants.httpCode.UNKNOWN, {data: {}}));
        });
    },
    getRecordList:async function(req,res){
        if(!baseCtrl.hasLogin(req, res)){
            return;
        }
        const SN = req.query.SN;
        const list = deviceCache.recordList[SN];
        // 获取媒体服务器信息
        const mediaServer = await mediaServerModel.getDefault();

        if(list&&list.items){
            list.items.forEach(function(item){
                item.address=item.Address.toString();
                item.deviceId = item.DeviceID.toString();
                item.endTime = item.EndTime.toString();
                item.filePath = item.FilePath.toString();
                item.name = item.Name.toString();
                item.secrecy = item.Secrecy.toString();
                item.startTime = item.StartTime.toString();
                item.type = item.Type.toString();
                item.flv = `http://${mediaServer.media_ip}:${mediaServer.http_port}/rtp/proxy/${item.filePath}.live.flv`;
                delete item.Address;
                delete item.DeviceID;
                delete item.EndTime;
                delete item.FilePath;
                delete item.Name;
                delete item.Secrecy;
                delete item.StartTime;
                delete item.Type;
            });
            res.send(Object.assign(constants.httpCode.OK, {data: list.items}));
        }else{
            res.send(Object.assign(constants.httpCode.OK, {data: []}));
        }
    },
    registry:function(req,res){
        if(!baseCtrl.hasLogin(req, res)){
            return;
        }
        let data = deviceCache.registry;
        res.send(Object.assign(constants.httpCode.OK,{data:data}));
    },
    control:function(req,res){
        if(!baseCtrl.hasLogin(req, res)){
            return;
        }
        //TODO:
        let data = {};
        res.send(Object.assign(constants.httpCode.OK,{data:data}));
    },
    zoom:function(req,res){
        if(!baseCtrl.hasLogin(req, res)){
            return;
        }
        //TODO:
        let data = {};
        res.send(Object.assign(constants.httpCode.OK,{data:data}));
    },
    move:function(req, res){
        let data = {};
        res.send(Object.assign(constants.httpCode.OK,{data:data}));
    }
};
module.exports=Channel;
